package xdpm.nhom16.DAO;

import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class AbstractDAO<DTO>
{
	public static final int DEFAULT_NUMBER = 0;
	protected SQLiteDatabase database = null;

	public AbstractDAO(SQLiteDatabase db)
	{
		this.database = db;
	}

	public ArrayList<DTO> getAll()
	{
		Cursor cursor = this.database.query(getTableName(), getNameColumns(), null, null, null, null, null);
		ArrayList<DTO> result = cursorToDTOs(cursor);
		cursor.close();
		return result;
	}

	protected ArrayList<DTO> cursorToDTOs(Cursor cursor)
	{
		ArrayList<DTO> result = new ArrayList<DTO>();
		if (null == cursor || !cursor.moveToFirst())
			return result;

		while (!cursor.isAfterLast())
		{
			DTO dto = cusorToDTO(cursor);
			result.add(dto);
			cursor.moveToNext();
		}
		return result;
	}

	public DTO getDTObyID(Object idValue)
	{
		String[] columns = getNameColumns();
		String selection = String.format("%s='%s'", getNameColumnId(), String.valueOf(idValue));
		Cursor cursor = database.query(getTableName(), columns, selection, null, null, null, null);
		if (cursor == null || !cursor.moveToFirst())
			return null;
		DTO dto = null;
		if (!cursor.isAfterLast())
		{
			dto = cusorToDTO(cursor);
		}
		cursor.close();

		return dto;
	}

	protected abstract String getTableName();

	protected abstract String getNameColumnId();

	protected abstract String[] getNameColumns();

	protected abstract DTO cusorToDTO(Cursor cursor);
}